﻿using GodSoft.Code;
using GodSoft.Common;
using GodSoft.Models;
using GodSoft.ViewModels;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;

namespace GodSoft.Controllers
{
    public class UserInfoController : BaseController
    {
        DataTable dt;
        GodSoftContext _context = new GodSoftContext();

        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 获取当前用户创建的 角色列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetRoleComboboxList()
        {
            //获取当前登录用户ID
            int currentUserID = Int32.Parse(Session["currentUserID"].ToString());

            var list = from i in _context.Roles
                       where i.CreateUserID == currentUserID
                       orderby i.ID
                       select new
                       {
                           RoleID = i.ID,
                           RoleName = i.RoleName
                       };

            return Json(list, JsonRequestBehavior.AllowGet);
        }
     

        [HttpPost]
        public ActionResult Regist_User_Role(Role role)
        {
            #region -----校验用户是否登录进入网站的-----
            //检验用户是否已经登录，如果登录则不执行，否则则执行下面的跳转代码
            if (Session["currentUserID"] != null)
            {
                int currentUserID = Int32.Parse(Session["currentUserID"].ToString());

                //角色不允许重名
                if (_context.Roles.Any(i => i.RoleName == role.RoleName))
                {
                    return Content("该角色名已被使用,请修改角色名!");
                }
                else
                {

                    role.CreateUserID = currentUserID;
                    role.SubTime = DateTime.Now;
                    _context.Roles.Add(role);
                    _context.SaveChanges();
                    return Content("OK");

                }
            }
            else
            {
                return Content("创建子角色失败!");

            }

            #endregion

        }

        [HttpPost]
        public ActionResult Regist(UserInfo UserInfo)
        {
            #region -----校验用户是否登录进入网站的-----
            //检验用户是否已经登录，如果登录则不执行，否则则执行下面的跳转代码
            if (Session["currentUserID"] != null)
            {
                int currentUserID = Int32.Parse(Session["currentUserID"].ToString());
                int RoleID = Convert.ToInt32(Request["RoleID"]);
                //如果存在该用户名，则返回提示信息，否则新增一个用户
                if (_context.UserInfoes.Any(i => i.UName == UserInfo.UName))
                {
                    return Content("该用户名已被使用,请修改用户名!");
                }
                else
                {
                    UserInfo.SubTime = DateTime.Now;
                    UserInfo.LastModifiedOn = DateTime.Now;
                    UserInfo.ParentID = currentUserID;
                    Role role = _context.Roles.Find(RoleID);
                    UserInfo.Roles.Add(role);
                    _context.UserInfoes.Add(UserInfo);
                    _context.SaveChanges();
                    return Content("OK");

                }
            }
            else
            {
                return Content("插入失败!");

            }

            #endregion

        }

        /// <summary>
        /// 显示用户拥有的权限信息
        /// </summary>
        /// <param name="ID">用户编号</param>
        /// <returns></returns>
        public ActionResult Get_User_ActionShow(int ID)
        {
             //获取用户信息
            UserInfo user = _context.UserInfoes.Include(i => i.Roles).Where(f => f.ID == ID).FirstOrDefault();

            if (user.Roles.Count() > 0)//用户拥有角色信息
            {
                //获取该用户所拥有的全部功能列表(Name,ID,ParentID)
                dt = PermissionAccess.GetActionInfoByUserID(ID);
                if (dt.Rows.Count > 0)//用户拥有权限信息
                {
                    ViewBag.UserID = ID;
                    return View();
                }
                else
                {
                    return Content("该用户没有权限!");
                }
            }
            else
            {
                return Content("该用户没有权限!");
            }
        }
        /// <summary>
        /// 生成该用户的权限树
        /// </summary>
        /// <param name="UserID">用户编号</param>
        /// <returns></returns>
        public ActionResult initTree(int UserID)
        {
            //获取用户信息
            UserInfo user = _context.UserInfoes.Include(i => i.Roles).Where(f => f.ID == UserID).FirstOrDefault();

            if (user.Roles.Count() > 0)//用户拥有角色信息
            {
                //获取该用户所拥有的全部功能列表(Name,ID,ParentID)
                dt = PermissionAccess.GetActionInfoByUserID(UserID);
                if (dt.Rows.Count>0)//用户拥有权限信息
                {
                    int ParentID = Int32.Parse(dt.Rows[0][2].ToString());//第一行第三列
                    string treedata = AddNode(dt, ParentID, 1);
                    return Content(treedata);
                }
                else
                {
                    return Content("该用户没有权限!");
                }

            }
            else
            {
                return Content("该用户没有权限!");
            }

           

        }

        /// <summary>  
        /// 无限递归，生成easyui tree可用的json数据 
        /// </summary>  
        /// <param name="ParentID">父id</param>  
        /// <param name="deep">开始深度，默认为1</param>  
        /// <returns></returns>  
        private string AddNode(DataTable dt, int ParentID, int deep)
        {
            string str = "";
            DataView dvTree = new DataView(dt);
            dvTree.RowFilter = "[ParentID]='" + ParentID + "'";//过滤出子权限

            int i = 0;
            int d = deep;
            foreach (DataRowView drv in dvTree)
            {

                if (i == 0)//如果是某一层的开始，需要“[”开始  
                {
                    if (d == 1)//如果深度为1,即第一层  
                        str = "[";
                    else//否则，为第二层或更深  
                        str = ",\"children\":[";
                }

                else
                    str = str + ",";



                str = str + "{";
                str = str + "\"id\":\"" + drv["ID"] + "\",";
                str = str + "\"text\":\"" + drv["ActionName"] + "\"";

               str = str + AddNode(dt, Convert.ToInt32(drv["ID"]), deep + 1);//递归  

                str = str + "}";
                i = i + 1;

                if (dvTree.Count == i)//如果某一层到了末尾,需要"]"结束  
                    str = str + "]";

            }

            return str;
        }


        /// <summary>
        /// 显示用户层级关系
        /// </summary>
        /// <param name="ID">用户编号</param>
        /// <returns></returns>
        public ActionResult Get_User_LevelShow(int ID)
        {     
            //获取全部用户ID，ParentID
            dt = PermissionAccess.GetAllUserIDAndParentID();
            string treedata = AddUserNode(dt, ID, 1);
            if (treedata != "")
            {
                ViewBag.UserID = ID;
                return View();
            }
            else
            {
                return Content("该用户没用子级用户!");
            }
          
        }
        /// <summary>
        /// 生成该用户的层级树
        /// </summary>
        /// <param name="UserID">用户编号</param>
        /// <returns></returns>
        public ActionResult initUserTree(int UserID)
        {
            //获取全部用户ID，ParentID
            dt = PermissionAccess.GetAllUserIDAndParentID();
            string treedata = AddUserNode(dt, UserID, 1);
            return Content(treedata);
        }
            


        

        /// <summary>  
        /// 无限递归，生成easyui tree可用的json数据 
        /// </summary>  
        /// <param name="ParentID">父id</param>  
        /// <param name="deep">开始深度，默认为1</param>  
        /// <returns></returns>  
        private string AddUserNode(DataTable dt, int ParentID, int deep)
        {
            string str = "";
            DataView dvTree = new DataView(dt);
            dvTree.RowFilter = "[ParentID]='" + ParentID + "'";//过滤出子用户

            int i = 0;
            int d = deep;
            foreach (DataRowView drv in dvTree)
            {

                if (i == 0)//如果是某一层的开始，需要“[”开始  
                {
                    if (d == 1)//如果深度为1,即第一层  
                        str = "[";
                    else//否则，为第二层或更深  
                        str = ",\"children\":[";
                }

                else
                    str = str + ",";



                str = str + "{";
                str = str + "\"id\":\"" + drv["ID"] + "\",";
                str = str + "\"text\":\"" + drv["UName"] + "\"";

                str = str + AddUserNode(dt, Convert.ToInt32(drv["ID"]), deep + 1);//递归  

                str = str + "}";
                i = i + 1;

                if (dvTree.Count == i)//如果某一层到了末尾,需要"]"结束  
                    str = str + "]";

            }

            return str;
        }

        public ActionResult GetAll()
        {
            //获取当前登录用户的ID号
            int currentUserID = Int32.Parse(Session["currentUserID"].ToString());
            //当前登录用户名(父用户名)
            //string currentUserName = _context.UserInfoes.Find(currentUserID).UName;

            int pageIndex = Request["page"] == null ? 1 : int.Parse(Request["page"]);
            int pageSize = Request["rows"] == null ? 10 : int.Parse(Request["rows"]);

            var temp = from i in _context.UserInfoes.Include(i => i.Roles).Where(i => i.ParentID == currentUserID)
                       orderby i.ID
                       select new
                       {
                           i.ID,
                           i.UName,
                           i.ParentID,
                           RoleID = i.Roles.FirstOrDefault().ID,//角色编号
                           RoleName = i.Roles.FirstOrDefault().RoleName,//角色名
                           i.Pwd,
                           i.Phone,
                           i.Mail,
                           i.SubTime,
                           i.LastModifiedOn,
                           i.DelFlag

                       };

            var list = temp.Skip((pageIndex - 1) * pageSize).Take(pageSize);
            var result = new { total = temp.Count(), rows = list };
            return Json(result, JsonRequestBehavior.AllowGet);

        }

        public ActionResult UpdateInfo(UserInfo UserInfo)
        {
            int RoleID = Convert.ToInt32(Request["RoleID"]);
            UserInfo userinfo = _context.UserInfoes.Include(i => i.Roles).Where(i => i.ID == UserInfo.ID).FirstOrDefault();


            userinfo.Roles = new List<Role>();
            userinfo.Roles.Add(_context.Roles.Find(RoleID));

            userinfo.LastModifiedOn = DateTime.Now;

            userinfo.Mail = UserInfo.Mail;
            userinfo.Phone = UserInfo.Phone;
            userinfo.UName = UserInfo.UName;
            userinfo.Pwd = UserInfo.Pwd;
            userinfo.DelFlag = UserInfo.DelFlag;

            _context.UserInfoes.Attach(userinfo);
            _context.Entry<UserInfo>(userinfo).State = EntityState.Modified;
            _context.SaveChanges();
            return Content("OK");
        }
        /// <summary>
        /// 删除多个用户
        /// </summary>
        /// <param name="deleteInfoID">需删除的用户的编号序列(用逗号连接)</param>
        /// <returns></returns>
        public ActionResult DeleteInfo(string deleteInfoID)
        {
            if (string.IsNullOrEmpty(deleteInfoID))
            {
                return Content("请选择您要删除的数据");
            }
            //截取传递过来的字符串的数字信息
            var idsStr = deleteInfoID.Split(',');

            List<int> deleteIDList = new List<int>();

            foreach (var ID in idsStr)
            {
                deleteIDList.Add(Convert.ToInt32(ID));
            }
            if (DeleteManyInfoes(deleteIDList) > 0)
            {
                return Content("OK");
            }
            else
            {
                return Content("删除失败，请您检查!");
            }

        }

        public int DeleteManyInfoes(List<int> DeleteIDList)
        {
            try
            {
                foreach (var id in DeleteIDList)
                {
                    DeleteUserWithRoleAndActions(id);//删除该用户的相关信息
                    //获取全部用户ID，ParentID
                    dt = PermissionAccess.GetAllUserIDAndParentID();
                    //递归删除该用户和其子用户的相关信息（含角色信息）
                    RecursionDelete(dt, id);

                }
                return 1;//删除成功
            }
            catch
            {
                return 0;//删除异常
            }

        }
        /// <summary>
        /// 递归删除
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="ParentID"></param>
        public void RecursionDelete(DataTable dt, int ParentID)
        {                 
            DataView dvUser = new DataView(dt);
            dvUser.RowFilter = "[ParentID]='" + ParentID + "'";//过滤出该用户的一级子用户

            foreach (DataRowView drv in dvUser)
            {
                int UserID = Convert.ToInt32(drv["ID"]);
                DeleteUserWithRoleAndActions(UserID);//删除子用户的相关信息
                RecursionDelete(dt, UserID);//递归删除

            }

        }
        /// <summary>
        /// 删除用户相关信息
        /// </summary>
        /// <param name="UserID">用户ID</param>
        public void DeleteUserWithRoleAndActions(int UserID)
        {
            UserInfo userInfo = _context.UserInfoes.Include(i => i.Roles).Where(f => f.ID == UserID).FirstOrDefault();
            if (userInfo.Roles.Count() > 0)//用户包含角色信息
            {
               // int RoleID = userInfo.Roles.First().ID;//获取角色编号

                userInfo.Roles = new List<Role>();//删除关联表(UserInfoRole)信息
                _context.UserInfoes.Remove(userInfo);//删除用户信息

                //Role role = _context.Roles.Include(i => i.ActionInfoes).Where(f => f.ID == RoleID).First();//得到角色拥有权限信息
                //role.ActionInfoes = new List<ActionInfo>();//删除关联表(ActionInfoRole)信息
                //_context.Roles.Remove(role);//删除角色信息

                _context.SaveChanges();
            }
            else //用户不含角色信息
            {
                userInfo.Roles = null;
                _context.UserInfoes.Remove(userInfo);//删除用户信息
                _context.SaveChanges();//保存
            }


        }


    }
}
